<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html>
	<head>
		<base href="/">
		<meta charset="utf-8">
		<title>TCL 商城</title>
		<link rel="stylesheet" href="index/home2.css">
		<link rel="stylesheet" href="fonts/iconfont.css">

	</head>
	<body id="#top">
		<div class="top-bar tonglan">
			<div class="top-nav-wrapper w">
				<div class="top-nav-left">

				</div>
				<div class="top-nav-right">

					<ul>
						<li><a href="page/index">首页</a></li><span></span>
						<li><a href="page/orderConfirm">我的订单</a></li> <span></span>
						<li><a href="page/cart">购物车</a></li> <span></span>
						<li class="lists-title"><a href="page/profile">个人中心</a></li><span></span>
						<li>
							<a href="#" id="logoutLink">退出登录</a>
						</li>
					</ul>
				</div>
			</div>
		</div>
		<div class="tonglan nav-bar">
			<div class="w">
				<div class="nav-logo">
					<img src="images/LOGO_2.png" alt="">
				</div>
				<div class="search">
					<input type="text" id="searchInput" placeholder="请输入想要的商品类型">
					<button type="button" id="searchButton">搜索</button>
				</div>
				<div class="menu-wrapper">
					<div class="menu-wrapper-left">
						<ul _id="categorylist">
							<li style="border-bottom: none;">
								<a href="page/index" >首页</a>
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>

<!--中部背景加左侧边栏-->
		<div class="tonglan menu-sub-container">
			<div class="menu-sub-img">
				<a>
					<img src="images/bjdt1.png" alt="">
				</a>

				<div class="w menu-sub">
					<div class="menu-sub-wrapper">
						<ul id="sub-category-list">

						</ul>
					</div>
				</div>
			</div>
		</div>
		<!-- 左中右布局 -->
		<div class="tonglan">
			<div class="w third">
				<div class="center">
					<a href="page/list">
						<img src="images/bg4.jpg" alt="">
					</a>
				</div>
			</div>
		</div>
		<!-- 左右布局 -->
		<div class="tonglan container-wrapper" id="product-container">



		</div>

		<div class="ricker">
			<div>
				<a><i class="iconfont icon-top" id="backToTopBtn" ></i>顶部</a>
			</div>
		</div>


		<script src="index/home2.js"></script>
	<script src="layui/layui.all.js"></script>
		<script type="text/html" _id="categoryitem">
			<li>
				<a href="page/list"></a>
				<div>
					<ul class="menu-main w">

					</ul>
				</div>
			</li>
</script>
		<script type="text/html" id="categorychild">
			<li>
				<a href="">
					<img src="" alt="">
					<span></span>
				</a>
			</li>
</script>
		<script type="text/html" id="productCategory">
			<div class="w container">
				<div class="title" id="{{id}}">{{name}}</div>
				<div class="container-left">
					<a href="page/list?category={{categoryName}}">
						<img src="{{img}}" alt="">
					</a>
				</div>
				<div class="container-center part">

				</div>
			</div>
		</script>

		<script type="text/html" id="sub-category">
			<li>
				<div class="menu-sub-title">
					<a href="page/list?category={{categoryName}}"> <!-- 修改链接，添加分类参数 -->
						{{categoryName}}
					</a>
					<ul class="sub-product-list">
						<!-- 子分类下的产品列表将动态插入 -->
					</ul>
				</div>
			</li>
		</script>

		<script type="text/html" id="sub-product">
			<li>
				<a href="page/detail?productid={{productid}}">
					<div>
						<img src="{{imageUrl}}" alt="">
					</div>
					<div>
						<p>{{productName}}</p>
						<span>{{price}}.00</span>
					</div>
				</a>
			</li>
		</script>

		<script>
			const $ = layui.$;
			$.ajax({
				url: 'category/list',
				data: { id: -1 },
				success: function (result) {
					let data = result.data;
					console.log(data);

					// 筛选出 pid 为 -1 的父级分类
					const parentCategories = data.filter(item => item.pid === -1);

					// 处理菜单分类列表
					parentCategories.forEach((parent) => {
						let item = $('script[_id="categoryitem"]').text();
						let $item = $(item);
						$item.children("a").text(parent.categoryname);
						$item.children("a").attr("href", `page/list?category=${parent.categoryname}`); // 修改链接，添加分类参数
						let $ul = $item.find("ul");

						// 发起请求获取子分类
						$.ajax({
							url: "category/getChildren",
							data: { id: parent.categoryid },
							success: function (res) {
								// 内层循环使用不同的变量名 j
								for (let j = 0; j < res.length; j++) {
									let childtext = $("#categorychild").text();
									let $child = $(childtext);
									$child.find("span").text(res[j].categoryname);
									$child.find("img").attr("src", res[j].imgurl);
									$child.find("a").attr("href", `page/list?category=${res[j].categoryname}`); // 修改链接，添加分类参数
									$ul.append($child);
								}
							},
							error: function (error) {
								console.error(`获取 ${parent.categoryname} 的子分类失败:`, error);
							}
						});

						$('ul[_id="categorylist"]').append($item);
					});

					// 处理产品分类展示
					const productContainer = $('#product-container');
					parentCategories.forEach((category) => {
						let categoryTemplate = $('#productCategory').text();
						let categoryHtml = categoryTemplate
								.replace('{{id}}', category.categoryid)
								.replace('{{name}}', category.categoryname)
								.replace('{{categoryName}}', category.categoryname)
								.replace('{{img}}', category.imgurl);
						let $category = $(categoryHtml);
						productContainer.append($category);

						// 获取该分类下的产品数据
						$.ajax({
							url: 'product/listByCategory', // 修改为新的接口路径
							data: { categoryname: category.categoryname },
							success: function (productsResult) {
								let products = productsResult.data;
								products = products.slice(0, 6);
								let $centerPart = $category.find('.container-center.part');
								products.forEach((product) => {
									let productHtml = `
                                    <div class="product-item">
                                        <a href="page/detail?productid=${product.productid}">
                                            <img src="${product.imgurl}" alt="${product.productname}">
                                        </a>
                                        <h5>${product.productname}</h5>
                                        <p>${product.description}</p>
                                        <span>${product.price}.00元</span>

                                    </div>
                                `;
									$centerPart.append(productHtml);
								});
							},
							error: function (error) {
								console.error(`获取 ${category.categoryname} 分类下的产品数据失败:`, error);
							}
						});
					});

					// 退出登录逻辑
					const logoutLink = document.getElementById('logoutLink');
					logoutLink.addEventListener('click', function (e) {
						e.preventDefault(); // 阻止默认的链接跳转行为
						// 弹出确认提示框
						if (confirm('确定要退出登录吗？')) {
							$.ajax({
								url: 'logout', // 后端退出登录的接口地址
								method: 'GET',
								success: function (response) {
									if (response.code === 200) {
										// 退出登录成功，给出提示并跳转到登录页面
										alert(response.msg);
										window.location.href = 'page/login';
									} else {
										// 退出登录失败，给出提示
										alert(response.msg);
									}
								},
								error: function (error) {
									console.error('退出登录失败:', error);
									alert('退出登录时发生错误，请稍后再试。');
								}
							});
						}
					});


					// 处理子分类展示
					const subCategoryList = $('#sub-category-list');
					const subCategories = data.filter(item => item.pid === -1);
					subCategories.forEach((subCategory) => {
						let subCategoryTemplate = $('#sub-category').text();

						let subCategoryHtml = subCategoryTemplate.replace(/{{categoryName}}/g, subCategory.categoryname);


						let $subCategory = $(subCategoryHtml);
						subCategoryList.append($subCategory);

						// 获取该子分类下的产品数据
						$.ajax({
							url: 'product/listByCategory',
							data: { categoryname: subCategory.categoryname },
							success: function (productsResult) {
								let products = productsResult.data;
								products = products.slice(0, 6);
								let $subProductList = $subCategory.find('.sub-product-list');
								products.forEach((product) => {
									let productTemplate = $('#sub-product').text();
									let productHtml = productTemplate
											.replace('{{productName}}', product.productname)
											.replace('{{imageUrl}}', product.imgurl)
											.replace('{{price}}', product.price)
								            .replace('{{productid}}', product.productid);
									$subProductList.append($(productHtml));
								});
							},
							error: function (error) {
								console.error(`获取 ${subCategory.categoryname} 子分类下的产品数据失败:`, error);
							}
						});
					});
				},
				error: function (error) {
					console.error('获取分类列表失败:', error);
				}
			});

			// 回到顶部按钮事件
			const backToTopBtn = document.getElementById('backToTopBtn');
			backToTopBtn.addEventListener('click', function () {
				window.scrollTo({
					top: 0,
					behavior: 'smooth'
				});
			});

			// 搜索功能
			const searchInput = document.getElementById('searchInput');
			const searchButton = document.getElementById('searchButton');

			searchButton.addEventListener('click', function () {
				const keyword = searchInput.value.trim();
				if (keyword) {
					window.location.href = `page/list?category=${encodeURIComponent(keyword)}`;
				}else {
					// 当输入为空时弹出提示框
					alert('请输入想要的商品类型');
				}
			});
		</script>
	</body>
</html>